package com.ruoyi.framework.web.service;

import javax.annotation.Resource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Component;

import com.ruoyi.common.core.domain.entity.UserInfo;
import com.ruoyi.common.core.domain.model.AppUser;
import com.ruoyi.common.core.redis.RedisCache;

@Component
public class AppLoginService {
	@Autowired
	private TokenService tokenService;

	@Resource
	private AuthenticationManager authenticationManager;

	@Autowired
	private RedisCache redisCache;

	/**
	 * 
	 * login:APP登录方法 <br/>  
	 * 
	 * @author tomcat
	 * @param userinfo
	 * @return 
	 * @since JDK 1.8
	 * date: 2022年4月2日 上午10:52:55 <br/>
	 */
	public AppUser login(UserInfo userinfo,String password) {
		// 用户验证
		Authentication authentication = null;
		try
		{
			// 该方法会去调用UserDetailsServiceImpl.loadUserByUsername

			authentication = authenticationManager
					.authenticate(new UsernamePasswordAuthenticationToken(userinfo.getPhone(), password));
		}catch (Exception e) {
			e.printStackTrace();
		}

		AppUser loginUser = (AppUser) authentication.getPrincipal();
		
		//创建token令牌
		loginUser.setToken(tokenService.createAppToken(loginUser));
		
		return loginUser;

	}
}
